const express = require('express')

const advRouter = express.Router()
const path = require('path')
const fs = require('fs')
const advListModel = require('../db/model/advListModel')
const { upload,getNowTime } = require('../utils')

advRouter.post('/addAdv', async (request, response) => {
    // 通过request.query来获取id
    let { _id } = request.query
    let fields
    try {
        fields = await upload(request, 'advPic')
    } catch (e) {
        response.json({
            code: 1,
            msg: '广告图片上传失败'
        })
    }
    try{
        let msg
        if (_id) {
            fields.updateTime = getNowTime()
            await advListModel.updateOne({ _id }, fields)
            msg: '广告编辑成功'
        } else {
            await advListModel.create(fields)
            msg: '广告添加成功'
        }
        response.json({
            code: 0,
            msg
        })
    }catch(e){
        response.json({
            code: 1,
            msg:'操作失败'
    })
    }

})
    

advRouter.get('/advList', async (request, response) => {
    let {keyword,pageIndex} = request.query
    console.log(keyword);
    let whereObj = {}
    if(whereObj){
        // RegExp正则
        whereObj.advTitle = new RegExp(keyword)
    }
    // 每页展示数量
    let pageSize = 3
    // 总共多少条
    let total = await advListModel.find(whereObj).count()
    // 总页数
    let totalPage = Math.ceil(total/pageSize)
    // 跳过几条
    let skipNum = (pageIndex-1)*pageSize
    let advList = await advListModel.find(whereObj).sort({ advOrder: -1, updateTime: -1 }).skip(skipNum).limit(pageSize).exec()
    response.json({
        code: 0,
        msg: '获取广告列表成功',
        data: { advList,totalPage,pageIndex }
    })
})

advRouter.get('/advList/:_id', async (request, response) => {
    let { _id } = request.params
    let adv = await advListModel.findOne({ _id })
    response.json({
        code: 0,
        msg: '获取成功',
        data: { adv }
    })
})



module.exports = advRouter